package JUC.阻塞队列;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author CKC
 * @DateTime 2021/4/1 18:30
 * <p>
 * 题目：一个初始变量为零，两个线程对其交替操作，一个加一一个减一，来5轮
 *
 * * 线程     操作(方法)      资源类
 * 2 判断     干活           通知
 * 3 防止虚假唤醒
 */


public class ProConsumer_TraditionDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    shareData.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();
        
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    shareData.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();
        
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    shareData.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();
    
    
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    shareData.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }
}

class ShareData { //资源类
    private int number;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //1.判断
            while (number != 0) condition.await();
            //2.干活
            number++;
            System.out.println(Thread.currentThread().getName() + "\t " + number);
            //3.通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //1.判断
            while (number == 0) condition.await();
            //2.干活
            number--;
            System.out.println(Thread.currentThread().getName() + "\t " + number);
            //3.通知唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    
}